package com.thiswhyme.openfeign.gson.config;

import com.thiswhyme.openfeign.gson.ThiswhymeGsonBuilder;
import com.thiswhyme.openfeign.gson.adapter.requestparam.GsonFeignFormatterRegistrar;
import com.thiswhyme.openfeign.gson.adapter.requestparam.JsonToObjectRequestParamConverter;
import feign.codec.Decoder;
import feign.codec.Encoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.openfeign.FeignFormatterRegistrar;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @description: feign-codec-gson配置
 * @author: thiswhyme
 * @date: 2020/8/17
 */
@Configuration
@EnableConfigurationProperties(GsonProperties.class)
public class GsonAutoConfiguration implements WebMvcConfigurer {

    /**
     * 配置feign对body体的decoder
     * @param converter
     * @return
     */
    @Bean
    public Decoder feignDecoder(GsonHttpMessageConverter converter) {
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter);
        return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
    }

    /**
     * 配置feign对body体的encoder
     * @param converter
     * @return
     */
    @Bean
    public Encoder feignEncoder(GsonHttpMessageConverter converter){
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter);
        return new SpringEncoder(objectFactory);
    }

    @Bean
    @ConditionalOnMissingBean(name = "gsonHttpMessageConverter")
    public GsonHttpMessageConverter gsonHttpMessageConverter(GsonProperties gsonProperties) {
        GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
        converter.setGson(ThiswhymeGsonBuilder.fetchCommonGson(gsonProperties));
        return converter;
    }

    /**
     * 将自定义的类型转换器添加进springmvc
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new JsonToObjectRequestParamConverter());
    }

    /**
     * 将自定义的类型转换器添加进feign
     * @return
     */
    @Bean
    public List<FeignFormatterRegistrar> feignFormatterRegistrar() {
        return Arrays.asList(new GsonFeignFormatterRegistrar());
    }
}
